package com.swz.dcrm.ui.home;


import android.animation.ValueAnimator;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.flyco.dialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.mobsandgeeks.saripaar.annotation.Or;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.CarModel;
import com.swz.dcrm.model.Clue;
import com.swz.dcrm.model.Dictionary;
import com.swz.dcrm.model.MultipleChoice;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;

import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.http.Body;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CarBrandViewModel;
import com.swz.dcrm.ui.viewmodel.CustomerManagementViewModel;
import com.swz.dcrm.util.Constant;
import com.swz.dcrm.util.Tool;
import com.swz.dcrm.widget.MultipleChoiceView;
import com.xh.baselibrary.callback.OnClickListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class AddCustomerFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.rg_wechat)
    RadioGroup rgWechat;
    @BindView(R.id.ll_wechat)
    LinearLayout llWechat;
    @BindView(R.id.rg_customer_type)
    RadioGroup rgCustomerType;
    @BindView(R.id.rg_sex)
    RadioGroup rgSex;
    @BindView(R.id.tv_right)
    TextView tvRight;

    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_tag)
    EditText etTag;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_intent_car)
    TextView tvIntentCar;
    @BindView(R.id.et_intent_car1)
    EditText tvIntentCar1;
    @BindView(R.id.et_intent_car2)
    EditText tvIntentCar2;
    @BindView(R.id.rg_loan)
    RadioGroup rgLoan;
    @BindView(R.id.et_city)
    EditText etCity;
    @BindView(R.id.tv_how_long)
    TextView tvHowLong;
    @BindView(R.id.tv_focus)
    TextView tvFocus;
    @BindView(R.id.tv_carPurchase)
    TextView tvCarPurchase;
    @BindView(R.id.et_customer_desc)
    EditText etCustomerDesc;
    @BindView(R.id.et_wechat)
    EditText etWechat;
    @BindView(R.id.et_compare)
    EditText etCompare;

    MultipleChoiceView<Dictionary> multipleChoiceView;

    private int height;
    private ValueAnimator valueAnimator;
    private Clue clue;


    private List<Dictionary> clueCustomerLevel;
    private List<Dictionary> carPurchase;
    private List<Dictionary> buyCarTime;
    private List<Dictionary> buyCarFocus;

    private ActionSheetDialog actionSheetDialog;

    private int selectCar;


    @Inject
    CustomerManagementViewModel customerManagementViewModel;
    @Inject
    CarBrandViewModel carBrandViewModel;

    public static AddCustomerFragment newInstance() {

        return new AddCustomerFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        customerManagementViewModel.getDictionary(Constant.DICTIONARY_clueCustomerLevel)
                .observe(this, listBaseResponse -> {
                    if (listBaseResponse.isSuccess()) {
                        clueCustomerLevel = listBaseResponse.getData();

                    }
                });
        customerManagementViewModel.getDictionary(Constant.DICTIONARY_carPurchase)
                .observe(this, listBaseResponse -> {
                    if (listBaseResponse.isSuccess()) {
                        carPurchase = listBaseResponse.getData();
                    }
                });
        customerManagementViewModel.getDictionary(Constant.DICTIONARY_buyCarFocus)
                .observe(this, listBaseResponse -> {
                    if (listBaseResponse.isSuccess()) {
                        buyCarFocus = listBaseResponse.getData();
                        List<MultipleChoice<Dictionary>> list = new ArrayList<>();
                        for (Dictionary dictionary : buyCarFocus) {
                            MultipleChoice<Dictionary> multipleChoice = new MultipleChoice<>();
                            multipleChoice.setT(dictionary);
                            multipleChoice.setTag(dictionary.getName());
                            list.add(multipleChoice);
                        }
                        List<String> hasChecked = null;
                        if (!TextUtils.isEmpty(clue.getBuyCarFocusDesc())) {
                            String[] s = clue.getBuyCarFocusDesc().split(",");
                            hasChecked = Arrays.asList(s);
                        }
                        multipleChoiceView = new MultipleChoiceView(getContext(), "请选择关注点", list, "确定", hasChecked);
                        multipleChoiceView.setOnClickListener(onClickListener);
                        multipleChoiceView.setOnDismissListener(() -> {
                            WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                            lp.alpha = 1f;
                            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                            getActivity().getWindow().setAttributes(lp);
                        });

                    }
                });
        customerManagementViewModel.getDictionary(Constant.DICTIONARY_buyCarTime)
                .observe(this, listBaseResponse -> {
                    if (listBaseResponse.isSuccess()) {
                        buyCarTime = listBaseResponse.getData();
                    }
                });
        carBrandViewModel.getSelectedCarModel().observe(this, carModel -> {
            if (carModel != null && selectCar > 0) {
                clue.setCarModelId(carModel.getId());
                tvIntentCar.setText(carModel.getName());
            }
        });

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_add_customer;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);

        height = Tool.dip2px(getActivity(), 54);
        String s = AddCustomerFragmentArgs.fromBundle(getArguments()).getClue();
        if (!s.equals("test")) {
            clue = new Gson().fromJson(s, Clue.class);
        }


        tvRight.setText(getString(R.string.add_customer_save));


        rgWechat.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_no:
                    clue.setWeixinFriend(false);
                    valueAnimator = ValueAnimator.ofInt(height, 0);
                    valueAnimator.addUpdateListener(animation -> {
                        ViewGroup.LayoutParams layoutParams = llWechat.getLayoutParams();
                        layoutParams.height = (int) animation.getAnimatedValue();
                        llWechat.setLayoutParams(layoutParams);
                    });
                    valueAnimator.setDuration(100);
                    valueAnimator.start();
                    break;
                case R.id.rb_yes:
                    clue.setWeixinFriend(true);
                    valueAnimator = ValueAnimator.ofInt(0, height);
                    valueAnimator.addUpdateListener(animation -> {
                        ViewGroup.LayoutParams layoutParams = llWechat.getLayoutParams();
                        layoutParams.height = (int) animation.getAnimatedValue();
                        llWechat.setLayoutParams(layoutParams);
                    });
                    valueAnimator.setDuration(100);
                    valueAnimator.start();
                    break;
            }
        });
        rgSex.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_boy:
                    clue.setSex(1);
                    break;
                case R.id.rb_girl:
                    clue.setSex(0);
                    break;
                case R.id.rb_unkown:
                    clue.setSex(null);
                    break;
            }
        });
        rgCustomerType.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_person:
                    clue.setCustomerType(1);
                    break;
                case R.id.rb_company:
                    clue.setCustomerType(2);
                    break;
            }
        });
        rgLoan.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_loan:
                    clue.setMortgage(true);
                    break;
                case R.id.rb_no_loan:
                    clue.setMortgage(false);
                    break;
            }
        });
        if (clue != null) {
            title.setText(getString(R.string.add_customer_title1));
            etName.setText(clue.getCusName());
            etPhone.setText(clue.getCusPhone());
            if(clue.getSex()==null){
                rgSex.check(R.id.rb_unkown);
            }else {
                if (clue.isBoy()) {
                    rgSex.check(R.id.rb_boy);
                } else {
                    rgSex.check(R.id.rb_girl);
                }
            }

            if (clue.getWeixinFriend()) {
                etWechat.setText(clue.getWechat());
                rgWechat.check(R.id.rb_yes);

            } else {
                rgWechat.check(R.id.rb_no);
            }
            if (!TextUtils.isEmpty(clue.getLevelDesc())) {
                tvLevel.setText(clue.getLevelDesc());
            }
            if (!TextUtils.isEmpty(clue.getImpressionLabel())) {
                etTag.setText(clue.getImpressionLabel());
            }
            if (clue.isCompany()) {
                rgCustomerType.check(R.id.rb_company);
            } else {
                rgCustomerType.check(R.id.rb_person);
            }
            if (clue.getMortgage()) {
                rgLoan.check(R.id.rb_loan);
            } else {
                rgLoan.check(R.id.rb_no_loan);
            }
            if (clue.getIntentCar() != null) {
                tvIntentCar.setText(clue.getIntentCar());
            }
            if (clue.getIntentCar2() != null) {
                tvIntentCar1.setText(clue.getIntentCar2());
            }
            if (clue.getIntentCar() != null) {
                tvIntentCar2.setText(clue.getIntentCar3());
            }
            if (!TextUtils.isEmpty(clue.getLicensePlateCity())) {
                etCity.setText(clue.getLicensePlateCity());
            }
            if (!TextUtils.isEmpty(clue.getCarPurchaseDesc())) {
                tvCarPurchase.setText(clue.getCarPurchaseDesc());
            }
            if (!TextUtils.isEmpty(clue.getBuyCarTimeDesc())) {
                tvHowLong.setText(clue.getBuyCarTimeDesc());
            }
            if (!TextUtils.isEmpty(clue.getBuyCarFocus())) {
                tvFocus.setText(clue.getBuyCarFocusDesc());
            }
            if (!TextUtils.isEmpty(clue.getRemark())) {
                etCustomerDesc.setText(clue.getRemark());
            }
            if (!TextUtils.isEmpty(clue.getCompareCarModel())) {
                etCompare.setText(clue.getCompareCarModel());
            }

        } else {
            clue = new Clue();
            title.setText(getString(R.string.add_customer_title));
            rgSex.check(R.id.rb_unkown);
            rgWechat.check(R.id.rb_yes);
            rgCustomerType.check(R.id.rb_person);
            rgLoan.check(R.id.rb_loan);
        }
        return true;
    }


    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }

    @OnClick(R.id.tv_right)
    public void save() {

        clue.setCusName(etName.getText().toString().trim());
        clue.setImpressionLabel(etTag.getText().toString().trim());
        clue.setRemark(etCustomerDesc.getText().toString().trim());
        clue.setCusPhone(etPhone.getText().toString().trim());
        if (clue.getWeixinFriend()) {
            clue.setWechat(etWechat.getText().toString().trim());
        }
        clue.setIntentCar(tvIntentCar.getText().toString().trim());
        clue.setIntentCar2(tvIntentCar1.getText().toString().trim());
        clue.setIntentCar3(tvIntentCar2.getText().toString().trim());
        clue.setCompareCarModel(etCompare.getText().toString().trim());
        clue.setLicensePlateCity(etCity.getText().toString().trim());


        if (clue.getId() != null) {
            customerManagementViewModel.updateClue(clue)
                    .observe(this, clueBaseResponse -> {
                        if (clueBaseResponse == null) {
                            return;
                        }
                        showToast(clueBaseResponse.getMsg());
                        backClick();
                    });
        } else {

            customerManagementViewModel.addClue(clue)
                    .observe(this, clueBaseResponse -> {
                        if (clueBaseResponse == null) {
                            return;
                        }
                        if (clueBaseResponse.isSuccess()) {
                            backClick();
                        } else {
                            showToast(clueBaseResponse.getMsg());
                        }
                    });
        }
    }

    @OnClick({R.id.ll_level, R.id.ll_how_long, R.id.ll_carPurchase, R.id.ll_focus})
    public void click(View view) {
        if (view.getId() == R.id.ll_focus) {
            WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
            lp.alpha = 0.4f;
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            getActivity().getWindow().setAttributes(lp);
            multipleChoiceView.showAtLocation(getView(), Gravity.BOTTOM, 0, 0);
            return;
        }
        List<String> list = new ArrayList<>();
        switch (view.getId()) {

            case R.id.ll_level:
                for (Dictionary dictionary : clueCustomerLevel) {

                    list.add(dictionary.getName());
                }
                break;
            case R.id.ll_carPurchase:
                for (Dictionary dictionary : carPurchase) {
                    list.add(dictionary.getName());
                }
                break;
            case R.id.ll_how_long:
                for (Dictionary dictionary : buyCarTime) {
                    list.add(dictionary.getName());
                }
                break;
        }
        String[] s = new String[]{};
        actionSheetDialog = new ActionSheetDialog(getContext(), list.toArray(s), null);
        actionSheetDialog.setOnOperItemClickL((parent, view1, position, id) -> {
            switch (view.getId()) {
                case R.id.ll_level:
                    tvLevel.setText(list.get(position));
                    clue.setLevel(clueCustomerLevel.get(position).getCode());
                    break;
                case R.id.ll_carPurchase:
                    tvCarPurchase.setText(list.get(position));
                    clue.setCarPurchase(carPurchase.get(position).getCode());
                    break;
                case R.id.ll_how_long:
                    tvHowLong.setText(list.get(position));
                    clue.setBuyCarTime(buyCarTime.get(position).getCode());
                    break;
            }
            actionSheetDialog.dismiss();
        });
        actionSheetDialog.isTitleShow(false);
        actionSheetDialog.show();
    }

    @OnClick({R.id.ll_intent_car})
    public void selectCar(View view) {
        selectCar=1;
        go(null, R.id.action_addCustomerFragment_to_carBrandFragment, null);
    }

    OnClickListener<List<Dictionary>> onClickListener = new OnClickListener<List<Dictionary>>() {
        @Override
        public void onItemClick(List<Dictionary> dictionaries) {
            if (dictionaries != null && dictionaries.size() > 0) {
                StringBuffer stringBuffer = new StringBuffer();
                StringBuffer stringBuffer1 = new StringBuffer();
                for (int i = 0; i < dictionaries.size(); i++) {

                    stringBuffer.append(dictionaries.get(i).getCode());
                    stringBuffer1.append(dictionaries.get(i).getName());
                    if (i != (dictionaries.size() - 1)) {
                        stringBuffer.append(",");
                        stringBuffer1.append(",");
                    }
                }
                clue.setBuyCarFocus(stringBuffer.toString());
                tvFocus.setText(stringBuffer1.toString());
            }
        }
    };
}
